package uk.co.kevinlockwood.kol.pages;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import uk.co.kevinlockwood.kol.droid.DroidHelpers;

public abstract class ApiPage extends KoLPage {
	protected JSONObject json = new JSONObject();
	protected Integer id = null;
	protected Integer count = null;
	protected Date since = null;
	protected String format = null;
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

	@Override
	public String pageName() {
		StringBuilder sb = new StringBuilder("api.php?for=koldroid_by_tenorkev&what=");
		sb.append(what());
		if (id != null) sb.append("&id=").append(id);
		if (count != null) sb.append("&count=").append(count);
		if (since != null) sb.append("&since=").append(df.format(since));
		if (format != null) sb.append("&format=").append(format);
		return sb.toString();
	}

	protected abstract String what();

	protected Integer getInt(String name) {
		Integer i = 0;
		try {
			i = json.getInt(name);
		} catch (JSONException e) {
			DroidHelpers.printStackTrace(e);
		}
		return i;
	}
	protected String getString(String name) {
		String s = "";
		try {
			s = json.getString(name);
		} catch (JSONException e) {
			DroidHelpers.printStackTrace(e);
		}
		return s;
	}

	public void buildFromHtml(List<String> html) {
		StringBuilder sb = new StringBuilder();
		for (String s : html) {
			sb.append(s);
		}
		try {
			json = new JSONObject(sb.toString());
		} catch (JSONException e) {
			DroidHelpers.printStackTrace(e);
		}
	}
}
